from rest_framework import serializers
from django.db.models import Count, Sum, Max, Min, Avg, Q, F
from django.db import transaction
import json, datetime, logging
from random import randint

from equity_admin.filters_goods import *
from users.models import *
from vouchers.models import *
from merchants.models import *
from equity_mall.utils.qiniu_storage import pic_upload

logger = logging.getLogger('django')


class LevelListSerializer(serializers.ModelSerializer):

    class Meta:
        model = Level
        fields = ('id', 'prov_name', 'city_name', 'district_name', 'branch_name', 'orgId', 'account', 'account_nine', 'level')


class GoodsTagActivityModelSerializer(serializers.ModelSerializer):

    activity_state_str = serializers.CharField(source='get_activity_state_display', read_only=True)
    create_user = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = GoodsTagActivity
        fields = ('id', 'goods_tag', 'activity_name', 'activity_state', 'activity_state_str', 'create_user', 'create_time')

    def get_create_user(self, obj):
        try:
            return obj.create_user.nickname
        except:
            return ''


class GoodsTagActivityLevelRelationModelSerializer(serializers.ModelSerializer):

    level = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = GoodsTagActivityLevelRelation
        fields = ('id', 'level')

    def get_level(self, obj):
        data = {}
        data['prov_name'] = ''
        data['city_name'] = ''
        data['district_name'] = ''
        data['branch_name'] = ''
        data['account'] = ''
        data['level'] = ''
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            data['account'] = level.account
            level = obj.level.level
            data['level'] = level
            # if level == 1:
            #     data['level'] = '省公司'
            # elif level == 2:
            #     data['level'] = '市公司'
            # elif level == 3:
            #     data['level'] = '区县'
            # elif level == 4:
            #     data['level'] =  '网点'
            # else:
            #     data['level'] = '信翔'
        except:
            pass
        return data


class GoodsCategoryModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = GoodsCategory
        fields = ['id', 'name', 'icon']


class GoodsListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    category = serializers.SerializerMethodField(read_only=True)
    merchant = serializers.SerializerMethodField(read_only=True)
    is_launched_str = serializers.CharField(source='get_is_launched_display', read_only=True)
    order_species_str = serializers.CharField(source='get_order_species_display', read_only=True)
    is_coupon_goods = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Goods
        fields = ('id', 'create_time', 'equityID', 'category', 'name', 'default_image', 'is_launched', 'is_launched_str', 'price',
                  'sales', 'remain_stock', 'merchant', 'is_coupon_goods', 'order_species', 'order_species_str')

    def get_is_coupon_goods(self, obj):
        try:
            alidiscountcoupon_id = self.context.get('alidiscountcoupon_id', None)
            if alidiscountcoupon_id:
                check_available = AliDiscountCouponGoodsAvailable.objects.filter(goods_id=obj.id, alidiscountcoupon_id=alidiscountcoupon_id)
                if check_available:
                    return 1
                else:
                    return 0
            else:
                return 0
        except:
            return 0

    def get_category(self, obj):
        try:
            return obj.category.name
        except:
            return ''

    def get_merchant(self, obj):
        data = {}
        data['name'] = ''
        data['short_name'] = ''
        data['id'] = ''
        try:
            merchant = obj.merchant
            data['name'] = merchant.name
            data['short_name'] = merchant.short_name
            data['id'] = merchant.id
        except:
            pass
        return data


class GoodsModifyApplymentModelSerializer(serializers.ModelSerializer):

    desc_detail = serializers.SerializerMethodField(read_only=True)
    goodsimage_set = serializers.SerializerMethodField(read_only=True)
    company_user = serializers.SerializerMethodField(read_only=True)
    applyment_type_str = serializers.CharField(source='get_applyment_type_display', read_only=True)

    class Meta:
        model = GoodsModifyApplyment
        fields = ('id', 'name', 'applyment_type', 'caption', 'desc_detail', 'price', 'market_price', 'default_image', 'goodsimage_set',
                  'manufacturer', 'specifications', 'applyment_type_str', 'company_user')

    def get_company_user(self, obj):
        try:
            return f'{obj.companyuser.nickname}({obj.companyuser.level.name})'
        except:
            return ''

    def get_desc_detail(self, obj):
        try:
            return json.loads(obj.desc_detail.replace("'", '"'))
        except:
            return obj.desc_detail

    def get_goodsimage_set(self, obj):
        try:
            return json.loads(obj.image_array)
        except:
            return obj.image_array


class GoodsRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    category = serializers.SerializerMethodField(read_only=True)
    merchant_name = serializers.SerializerMethodField(read_only=True)
    is_launched_str = serializers.CharField(source='get_is_launched_display', read_only=True)
    goodsimage_set = serializers.SerializerMethodField(read_only=True)
    desc_detail = serializers.SerializerMethodField(read_only=True)
    applyment = serializers.SerializerMethodField(read_only=True)
    reject_reason = serializers.SerializerMethodField(read_only=True)
    order_type_str = serializers.CharField(source='get_order_type_display', read_only=True)
    order_species_str = serializers.CharField(source='get_order_species_display', read_only=True)

    class Meta:
        model = Goods
        fields = ('id', 'create_time', 'equityID', 'category', 'name', 'default_image', 'is_launched', 'is_launched_str', 'price',
                  'sales', 'remain_stock', 'merchant_name', 'manufacturer', 'specifications', 'caption', 'goodsimage_set', 'desc_detail',
                  'market_price', 'merchant_id', 'applyment', 'reject_reason', 'goods_tag', 'order_type', 'order_type_str',
                  'is_group', 'group_price', 'group_order_num', 'group_limit_time', 'group_limit_type', 'order_species', 'order_species_str',
                  'proof', 'desc_pack')

    def get_reject_reason(self, obj):
        try:
            if obj.is_launched == 3:
                applyment = obj.goodsmodifyapplyment_set.all().filter(applyment_status=3).last()
                return applyment.reject_reason
            else:
                return ''
        except:
            return ''

    def get_applyment(self, obj):
        try:
            if obj.is_launched == 2:
                applyment = obj.goodsmodifyapplyment_set.all().filter(applyment_status=1).first()
                return GoodsModifyApplymentModelSerializer(applyment).data
            else:
                return {}
        except:
            return {}

    def get_desc_detail(self, obj):
        try:
            return json.loads(obj.desc_detail.replace("'", '"'))
        except:
            return obj.desc_detail

    def get_goodsimage_set(self, obj):
        data = []
        try:
            goodsimage_set = obj.goodsimage_set.all()
            for goodsimage in goodsimage_set:
                data.append(goodsimage.image.url)
        except:
            pass
        return data

    def get_category(self, obj):
        try:
            return obj.category.name
        except:
            return ''

    def get_merchant_name(self, obj):
        try:
            return obj.merchant.name
        except:
            return ''


class LaunchedGoodsListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    goodsinfo = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    is_launched_str = serializers.CharField(source='get_is_launched_display', read_only=True)

    class Meta:
        model = LaunchedGoods
        fields = ('id', 'create_time', 'point', 'goodsinfo', 'sales', 'level_name', 'is_launched', 'is_launched_str', 'stock')

    def get_goodsinfo(self, obj):
        data = {}
        data['default_image'] = ''
        data['name'] = ''
        data['category'] = ''
        data['equityID'] = ''
        data['merchant_name'] = ''
        data['sales'] = ''
        data['remain_stock'] = ''
        try:
            goods = obj.goods
            data['default_image'] = goods.default_image.url
            data['name'] = goods.name
            data['category'] = goods.category.name
            data['equityID'] = goods.equityID
            data['merchant_name'] = goods.merchant.name
            data['sales'] = goods.sales
            data['remain_stock'] = goods.remain_stock
        except:
            pass
        return data

    def get_level_name(self, obj):
        try:
            if obj.is_self == 0:
                return obj.level.name
            else:
                return '自营'
        except:
            return ''